package com.msmall.community.bbs.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.exception.DataNotFoundException;
import com.msmall.base.pager.MatchType;
import com.msmall.base.pager.PaginationSupport;
import com.msmall.base.service.impl.BaseManagerImpl;
import com.msmall.community.bbs.dao.MasterDao;
import com.msmall.community.bbs.model.Board;
import com.msmall.community.bbs.model.Master;
import com.msmall.community.bbs.model.Topic;
import com.msmall.community.bbs.service.BoardManager;
import com.msmall.community.bbs.service.MasterManager;
import com.msmall.community.user.model.UserInfo;
import com.msmall.community.user.service.UserManager;

public class MasterManagerImpl extends BaseManagerImpl<Master, Long> implements MasterManager{

	private static final Log logger = LogFactory.getLog(MasterManagerImpl.class);
	
	private MasterDao masterDao;

	private BoardManager boardManager;
	
	private UserManager userManager;
	
	public void setMasterDao(MasterDao masterDao) {
		this.masterDao = masterDao;
	}
	
	public void setBoardManager(BoardManager boardManager) {
		this.boardManager = boardManager;
	}
	
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public List<Master> getMastersByBoardId(Long boardId) throws DataNotFoundException{
		return masterDao.findMasterByBoardId(boardId);
	}
	public Master getMaster(Long boardId, Long userid) throws DataNotFoundException{
		return masterDao.findMaster(boardId, userid);
	}

	public List<Master> findMasterByThreadId(Long threadId) throws DataNotFoundException {
		return masterDao.findMasterByThreadId(threadId);
	}

	public List<Master> findMasterByTopicId(Long topicId) throws DataNotFoundException {
		return masterDao.findMasterByTopicId(topicId);
	}
	public List<Master> findMasterByUserid(Long userid) throws DataNotFoundException{
		return masterDao.findMasterByUserid(userid);
	}
	
	public void delete(String masterIds) {
		if(null == masterIds || "".equals(masterIds))
			return;
		String[] masterIdx = masterIds.split(",");
		
		for(int i = 0; i < masterIdx.length; i++){
			if(null == masterIdx[i] || "".equals(masterIdx[i].trim())){
				continue;
			}
			Long id = Long.valueOf(masterIdx[i].trim());
			Master master = (Master) masterDao.get(Master.class, id);
			Long boardId = master.getBoardId();
			Long userid = master.getUserid();
			int level = master.getLevels();
			if(level == 3){ // 如果是普通管理员，只删除此记录
				masterDao.remove(Master.class, id);
			}
			if(level == 2){ // 如果是高级管理员，则同时删除此管理员对此版区的子版区的管理权限
				try {
					iteratorMasterReduce(boardId, userid, 2);
				} catch (Exception e) {
					logger.error(e.getStackTrace());
				}
			}
			if(level == 1){ //如果是超级管理员，全部删除
				Iterator it = boardManager.getAllBoard().iterator();
				while(it.hasNext()){
					Board board = (Board) it.next();
					if(board.getParentId().compareTo(0l) == 0){
						try {
							iteratorMasterReduce(board.getBoardId(), userid, 1);
						} catch (Exception e) {
							logger.error(e.getStackTrace());
						}
					}
				}
			}
			
		}
	}
	// 递归解除此版区和子版区管理权限
	public void iteratorMasterReduce(Long boardId, Long userid, int level) throws DataNotFoundException{
		Master master = this.getMaster(boardId, userid);
		if(master != null){
			masterDao.remove(Master.class, master.getMasterId());
			List<Board> children = masterDao.getByProperty(Board.class, "parentId", MatchType.EQ, String.valueOf(boardId));
			if(children != null && children.size() > 0){
				for(int j = 0; j < children.size(); j++){
					Board board = children.get(j);
					Long bId = board.getBoardId();
					iteratorMasterReduce(bId, userid, level);
				}
			}
		}
	}
	//TODO 版主信息是虚假的
	public void search(PaginationSupport page, String searchType, String searchValue) {
		if(searchType.equals("1")){ //用户名
			searchUserByUsername(page, searchValue);
		}else if(searchType.equals("2")){ //用户昵称
			searchUserByNickname(page, searchValue);
		}
		/*
		List<UserInfo> list = new ArrayList<UserInfo>();
		UserInfo u= new UserInfo();
		u.setNickname("3");
		list.add(u);
		for(int i =0 ;i<10 ; i++){
			UserInfo u1= new UserInfo();
			u1.setNickname("nickname" + i);
			list.add(u1);
		}
		page.setPageSize(10);
		page.setTotalCount(list.size());
		int start = page.getStartIndex();
		int end = start + 10 > list.size()?list.size():start + 10;
		page.setItems(list.subList(start, end));
		*/
	}

	public void searchUserByUsername(PaginationSupport page, String username){
		page.setClazz(UserInfo.class);
		page.setPageSize(20);
		String queryString = " from UserInfo u where u.username='" + username + "' order by u.userid desc";
		page.setQueryString(queryString);
		masterDao.getPagination(page);
	}
	public void searchUserByNickname(PaginationSupport page, String nickname){
		page.setClazz(UserInfo.class);
		page.setPageSize(20);
		String queryString = " from UserInfo u where u.nickname like '%" + nickname + "%' order by u.userid desc";
		page.setQueryString(queryString);
		masterDao.getPagination(page);
	}
	public void setMaster(Long boardId, Long userid, String level) {
		UserInfo user = userManager.getByUserid(userid);
		String nickname = user.getNickname();
		try{
			if("1".equals(level)){
				Iterator it = boardManager.getAllBoard().iterator();
				while(it.hasNext()){
					Board board = (Board) it.next();
					if(board.getParentId().compareTo(0l) == 0){
						iteratorMaster(board.getBoardId(), userid, nickname, "1");
					}
				}
			}
			if("2".equals(level)){
				iteratorMaster(boardId, userid, nickname, "2");
			}
			if("3".equals(level)){ // 同时删除此用户对其他版区的管理功能
				List<Master> masters = findMasterByUserid(userid);
				boolean tag = false;
				if(masters != null && masters.size() > 0){
					for(int j = 0 ; j < masters.size(); j ++){
						Master m = masters.get(j);
						if(m.getBoardId().compareTo(boardId) == 0){ // 如果此用户已经具有管理此版区的功能，则更新权限等级
							m.setLevels(Integer.valueOf(level));
							m.setNickname(nickname);
							masterDao.save(m);
							tag = true;
						}else{
							masterDao.remove(Master.class, m.getMasterId()); // 删除对其他版区的管理功能
						}
					}
				}
	
				if(!tag){
					Master master = new Master();
					master.setLevels(3);
					master.setUserid(userid);
					master.setNickname(nickname);
					Board board = (Board) masterDao.get(Board.class, boardId);
					master.setBoardId(boardId);
					masterDao.save(master);
				}
			}
		}catch(Exception e){
			
		}
	}
	// 递归增加管理权限
	private void iteratorMaster(Long boardId, Long userid, String nickname, String level){
		List<Board> childs = boardManager.getChildBoard(boardId); //子版区
		Board board = (Board) masterDao.get(Board.class, boardId);
		try {
			Master master = this.getMaster(boardId, userid);
			if(master == null){
				Master newm = new Master();
				newm.setLevels(Integer.valueOf(level));
				newm.setUserid(userid);
				newm.setBoardId(boardId);
				newm.setNickname(nickname);
				masterDao.save(newm);
			}else{// 如果此用户已经是此版区的版主，更新版主等级
				master.setLevels(Integer.valueOf(level));
				master.setNickname(nickname);
				masterDao.save(master);
			}
		} catch (DataNotFoundException e) {
		}
		for(int i = 0; i < childs.size(); i ++){
			Board bx = childs.get(i);
			iteratorMaster(bx.getBoardId(), userid, nickname,level);
		}
	}

	public void move(Long boardId, Long toBoardId, Long topicId) {
		Topic topic = (Topic)masterDao.get(Topic.class, topicId);
		topic.setBoardid(toBoardId);
		masterDao.saveObject(topic);
	}

	/**
	 * 当创建一个版区时， 自动将超级版主和高级版主的权限授权(?)
	 * 当创建或者更新版区时，修改此版区的版主信息
	 */
	public void saveBoardMaster(Long boardId){
		Board board = (Board) masterDao.get(Board.class, boardId);
		// 如果此版区的高级版主和父版区的高级版主相同，则删除此版区的高级版主以及此版区的子版区的高级版主， 普通版主不变
		try {
			List masters = getMastersByBoardId(boardId); //此版区的版主
		//	List parentBoardMasters = getMastersByBoardId(board.getParentId()); //父版区的版主
			if(null != masters && masters.size() > 0){
				for(int k = 0; k < masters.size(); k ++){
					Master temp = (Master) masters.get(k);
					if(temp.getLevels().intValue() == 2){ //此版区的高级版主
						Long userid = temp.getUserid();
						Master pMaster = getMaster(board.getParentId(), userid); //此版区的高级版主是否也是父版区的版主
						if(pMaster != null){
						//	masterDao.remove(Master.class, temp.getMasterId());
							iteratorMasterReduce(boardId, userid, 2);
						}
					}
				}
			}
		} catch (Exception e) {
		}
		
		//查找所有超级版主，授予管理此版区的权限
		List<Master> lm1 = masterDao.getByProperty(Master.class, "level", MatchType.EQ, "1");
		String userids = "";
		try {
		if(lm1 != null && lm1.size() > 0){
			for(int i = 0; i < lm1.size(); i++){
				Master m = lm1.get(i);
				Long userid = m.getUserid();//超级版主名称
				if(userids.indexOf(String.valueOf(userid)) != -1){ // 重复的用户不添加
					continue;
				}else{
					userids +=("," + userid);
					Master mx = this.getMaster(boardId, userid);
					// 此超级版主是否已经管理了此版区
					if(mx != null){
						mx.setLevels(1);
						masterDao.saveObject(mx);
					}else{
						Master master = new Master();
						master.setBoardId(board.getBoardId());
						master.setLevels(1);
						master.setUserid(userid);
						masterDao.saveObject(master);
					}
				}
			}
		}
		} catch (DataNotFoundException e) {
			e.printStackTrace();
		} 
		//查找父版区的高级版主，授予管理此版区的权限,只需要查找到上一级的版区的高级版主就可以
		userids = "";
		List<Board> pbs = masterDao.getByProperty(Board.class, "boardId", MatchType.EQ, String.valueOf(board.getParentId()));
		if(pbs != null && pbs.size() > 0){
			Board parent = pbs.get(0); // 父版区
			try {
				List ms = getMastersByBoardId(parent.getBoardId()); // 父版区所有版主
				List<Master> lm2 = new ArrayList<Master>(); //父版区高级版主
				if(null != ms && ms.size() > 0){
					for(int k = 0; k < ms.size(); k ++){
						Master temp = (Master) ms.get(k);
						if(temp.getLevels().intValue() == 2){ //父版区高级版主
							
							Long userid = temp.getUserid();//超级版主名称
							if(userids.indexOf(String.valueOf(userid)) != -1){ // 重复的用户不添加
								continue;
							}else{
								userids +=("," + userid); // 所有父版区的高级版主名称
							}
						}
					}
				}
				String[] useridx = userids.split(",");
				for(int i = 0; i < useridx.length; i++){
					String masterid = useridx[i];
					if(null != masterid && !"".equals(masterid)){
						Master master = new Master();
						master.setBoardId(board.getBoardId());
						master.setLevels(2);
						master.setUserid(Long.valueOf(masterid));
						masterDao.saveObject(master);
					}
				}
			} catch (Exception e) {
			}
		}
	}
}
